#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/select.h>
using namespace std;
static const string ip = "127.0.0.1";
static const uint16_t port = 8080;
int main(int argc, char *argv[])
{
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    server.sin_port = htons(port);
    connect(socket_fd, (struct sockaddr *)&server, sizeof(server));
    fd_set set;
    while (true)
    {
        FD_ZERO(&set);
        FD_SET(STDIN_FILENO, &set);
        FD_SET(socket_fd, &set);
        select(10, &set, nullptr, nullptr, nullptr);
        if (FD_ISSET(STDIN_FILENO, &set))
        {
            char buffer[1024] = {0};
            int ret_read = read(STDIN_FILENO, buffer, sizeof(buffer));
            send(socket_fd, buffer, ret_read, 0);
        }
        if (FD_ISSET(socket_fd, &set))
        {
            char buffer[1024] = {0};
            int ret_recv = recv(socket_fd, buffer, sizeof(buffer), 0);
            if (ret_recv <= 0)
            {
                cout << "服务端主动关闭了链接, 我也退出" << endl;
                break;
            }
            buffer[ret_recv] = 0;
            cout << "buffer : " << buffer << endl;
        }
    }
    close(socket_fd);
    return 0;
}